﻿#region Using Directives

using System;
using System.IO;
using System.Windows.Forms;
using System.Globalization;
using Microsoft.Practices.ComponentModel;
using Microsoft.Practices.RecipeFramework;
using Microsoft.Practices.RecipeFramework.Library;
using Microsoft.Practices.RecipeFramework.Services;
using Microsoft.Practices.RecipeFramework.VisualStudio;
using Microsoft.Practices.RecipeFramework.VisualStudio.Templates;
using EnvDTE;
using System.Reflection;

#endregion

namespace SteriaMummert.SharePoint.SoftwareFactoryLite.Actions
{
    /// <summary>
    /// </summary>
    [ServiceDependency(typeof(DTE))]
    public class CreateMultipleFileTemplates : ConfigurableAction
    {
        private string _FileNameProperty = ""; 
        private string _SourceTemplateFile = ""; 
        private object[] _FileCollection = null; 
        private string destFolder = "";
        private string _ChangeExtensionTo = "";
       
        [Input(Required = true)]
        public string FileNameProperty
        {
            get { return _FileNameProperty; }
            set { _FileNameProperty = value; }
        }

        [Input(Required = false)]
        public string ChangeExtensionTo
        {
            get { return _ChangeExtensionTo; }
            set { _ChangeExtensionTo = value; }
        }

        

        [Input(Required = true)]
        public string SourceTemplateFile
        {
            get { return _SourceTemplateFile; }
            set { _SourceTemplateFile = value; }
        }

        [Input(Required = true)]
        public object[] FileCollection
        {
            get { return _FileCollection; }
            set { _FileCollection = value; }
        }

        [Input(Required = true)]
        public string TargetFolder
        {
            get { return destFolder; }
            set { destFolder = value; }
        }

        [Input(Required = true)]
        public Project Project
        {
            get
            {
                return this.project;
            }
            set
            {
                this.project = value;
            }
        }
        private Project project;

        protected string GetBasePath()
        {
            return base.GetService<IConfigurationService>(true).BasePath;
        }

        private string GetTemplateBasePath()
        {
            return new DirectoryInfo(this.GetBasePath() + @"\Templates").FullName;
        }

        public ProjectItems WhereToAdd()
        {
            ProjectItems whereToAdd;
            if ((destFolder != String.Empty) && (destFolder != null))
            {

                //only works for a single foldername
                ProjectItem _folder = DteHelper.FindItemByName(this.Project.ProjectItems, destFolder, true);
                if (_folder != null)
                {
                    whereToAdd = _folder.ProjectItems;
                }
                else
                {
                    ProjectItems pitems = this.Project.ProjectItems;

                    string projectpath = Project.Properties.Item("FullPath").Value.ToString();

                    //folder doesnt exist
                    //create the folder
                    char[] sep = { '\\' };
                    string[] folders = destFolder.Split(sep);
                    for (int i = 0; i < folders.Length; i++)
                    {
                        projectpath += folders[i] + "\\";
                        //does the folder already exist?
                        _folder = DteHelper.FindItemByName(pitems, folders[i], true);
                        if (_folder != null)
                        {
                            //folder exists
                            pitems = _folder.ProjectItems;
                        }
                        else
                        {   //create folder
                            try
                            {
                                _folder = pitems.AddFolder(folders[i], Constants.vsProjectItemKindPhysicalFolder);
                                pitems = _folder.ProjectItems;
                            }
                            catch (Exception ex)
                            {
                                _folder = pitems.AddFromDirectory(projectpath);
                                pitems = _folder.ProjectItems;
                            }
                        }
                    }
                    whereToAdd = _folder.ProjectItems;
                }
            }
            else
            {
                whereToAdd = this.Project.ProjectItems;
            }
            return whereToAdd;
        }
        
        public override void Execute()
        {
            string templateBasePath = GetTemplateBasePath();
            string template = SourceTemplateFile;

            if (FileCollection != null)
            {
                foreach (object obj in FileCollection)
                {
                    try
                    {
                        PropertyInfo propinfo = obj.GetType().GetProperty(FileNameProperty);
                        string targetFilename = (string)propinfo.GetValue(obj, null);

                        if (_ChangeExtensionTo != "")
                        {
                            targetFilename = targetFilename.Substring(0, targetFilename.LastIndexOf('.'));
                            targetFilename += "." + _ChangeExtensionTo;
                        }

                        //filename is jetzt z.B. test.aspx
                        if (!Path.IsPathRooted(template))
                        {
                            template = Path.Combine(templateBasePath, template);
                        }

                        template = new FileInfo(template).FullName;
                        if (!template.StartsWith(templateBasePath))
                        {
                            throw new ArgumentException("Exception");
                        }

                        ProjectItems whereToAdd = WhereToAdd();
                        ProjectItem _ProjectItem = whereToAdd.AddFromTemplate(template, targetFilename);
                    }
                    catch (Exception ex)
                    {
                        throw new Exception(ex.ToString());
                    }
                }
            }

            /*
            DTE vs = base.GetService<DTE>(true);
            string path = Path.GetTempFileName();
            using (StreamWriter writer = new StreamWriter(path, false))
            {
                writer.WriteLine(Content);
            }
            ProjectItems whereToAdd = WhereToAdd();
            this.ProjectItem = whereToAdd.AddFromTemplate(path, this.TargetFileName);
            if (this.Open)
            {
                Window window = this.ProjectItem.Open("{00000000-0000-0000-0000-000000000000}");
                window.Visible = true;
                window.Activate();
            }
            File.Delete(path);
             * */
        }

        /// <summary>
        /// Removes the previously added reference, if it was created
        /// </summary>
        public override void Undo()
        {
        }
    }
}